import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import InterestSelection from '../views/InterestSelection.vue'
import Publish from '../views/Publish.vue'
import MyContent from '../views/MyContent.vue'
import ContentDetail from '../views/ContentDetail.vue'
import DingtalkCallback from '../views/DingtalkCallback.vue'
import { userAPI } from '../api'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/dingtalk/callback',
    name: 'DingtalkCallback',
    component: DingtalkCallback
  },
  {
    path: '/interest',
    name: 'InterestSelection',
    component: InterestSelection,
    meta: { requiresAuth: true }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/publish',
    name: 'Publish',
    component: Publish,
    meta: { requiresAuth: true }
  },
  {
    path: '/my-content',
    name: 'MyContent',
    component: MyContent,
    meta: { requiresAuth: true }
  },
  {
    path: '/content/:id',
    name: 'ContentDetail',
    component: ContentDetail,
    meta: { requiresAuth: true }
  },
  {
    path: '/',
    redirect: '/login'  // 默认跳转到登录页
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 检查登录状态和兴趣标签选择
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果访问登录页且已有token，跳转到主页
  if (to.path === '/login' && token) {
    next('/home')
    return
  }
  
  // 如果需要认证的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      // 没有token，跳转到登录页
      next('/login')
      return
    }
    
    // 有token，检查是否选择了兴趣标签（但不包括登录页和兴趣选择页）
    if (token && to.path !== '/interest' && to.path !== '/login') {
      try {
        const response = await userAPI.getUserTags()
        
        // 如果用户未选择标签，跳转到兴趣选择页
        if (response.data.code === 0 && (!response.data.data || response.data.data.length === 0)) {
          next('/interest')
          return
        }
      } catch (error) {
        console.error('检查用户标签失败:', error)
        if (error.response?.status === 401) {
          // Token失效，清除本地存储并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          next('/login')
          return
        }
      }
    }
  }
  
  next()
})

export default router
